package com.link4a.doms.web.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.link4a.doms.Constants;
import com.link4a.doms.exception.BusinessException;
import com.link4a.doms.exception.ValidationException;
import com.link4a.doms.model.Driver;
import com.link4a.doms.service.DriverService;
import com.link4a.doms.vo.DriverCondition;
import com.link4a.doms.web.ControllerSupport;
import com.link4a.doms.web.JsonResult;
import com.link4a.doms.web.auth.Privilege;

@Controller
@RequestMapping("driver")
public class DriverController extends ControllerSupport{

	@Autowired
	private DriverService driverService;
	
	@RequestMapping
	@ResponseBody
	public JsonResult findPage(@RequestBody DriverCondition condition){
		return success(driverService.findPage(condition));
	}
	
	@RequestMapping
	@ResponseBody
	public JsonResult list(@RequestParam(value="searchstr") String keyword){
		return success(driverService.listByKeyword(keyword));
	}
	
	@RequestMapping("/get/{id}")
	@ResponseBody
	public JsonResult get(@PathVariable int id){
		return success(driverService.findById(id));
	}
	
	@RequestMapping(value = "/delete/{id}", method=RequestMethod.POST)
	@ResponseBody
	@Privilege(Constants.DRIVER_CUD)
	public JsonResult delete(@PathVariable int id) {
		try {
			driverService.delete(id);
			return success();
		} catch (BusinessException e) {
			return fail(e.getMessage());
		}
	}
	
	@RequestMapping(method=RequestMethod.POST)
	@ResponseBody
	@Privilege(Constants.DRIVER_CUD)
	public JsonResult save(@RequestBody Driver driver) {
		try {
			driverService.save(driver);
			return success();
		} catch (ValidationException e) {
			return result(e.getCode());
		}
	}
	
	@RequestMapping
	@Privilege(Constants.DRIVER_INDEX)
	public ModelAndView index(@RequestParam(value = "cookie", required = false) Boolean cookie){
		ModelAndView mav = new ModelAndView("/business/driver");
		mav.addObject("cookie", cookie);
		return mav;
	}
	
	@RequestMapping
	@Privilege(Constants.DRIVER_CUD)
	public ModelAndView add(){
		ModelAndView mav = new ModelAndView("/business/driverForm");
		return mav;
	}
	
	@RequestMapping("/edit/{id}")
	@Privilege(Constants.DRIVER_CUD)
	public ModelAndView edit(@PathVariable int id){
		ModelAndView mav = new ModelAndView("/business/driverForm");
		mav.addObject("id", id);
		return mav;
	}
}	
